package com.hulman.oms.web;

import com.hulman.oms.bean.DeviceFile;
import com.hulman.oms.bean.Result;
import com.hulman.oms.service.DeviceFileService;
import com.hulman.oms.util.FileUtil;
import com.hulman.oms.util.StringUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class DeviceFileController
{

    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private DeviceFileService deviceFileService;

    @Autowired
    private HttpServletResponse response;

    @PostConstruct
    public void init()
    {
        File fileDir = new File(fileHome);
        if (!fileDir.exists())
        {
            fileDir.mkdirs();
            log.info("Create file home:{}", fileHome);
        }
    }

    @GetMapping("/device-files/{id}")
    public Result findDeviceFileById(@PathVariable Integer id)
    {
        DeviceFile deviceFile = deviceFileService.selectByPrimaryKey(id);
        return new Result(deviceFile);
    }

    @GetMapping("/device-files")
    public Result findDeviceFiles(Integer page, Integer limit, String name, Integer userId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("userId", userId);
        map.put("name", name);
        return deviceFileService.findDeviceFilesResult(map);
    }

    @DeleteMapping("/device-files/{id}")
    public Result deleteDeviceFileById(@PathVariable Integer id)
    {
        DeviceFile deviceFile = deviceFileService.selectByPrimaryKey(id);
        if (deviceFile != null)
        {
            String fileName = fileHome + deviceFile.getStorageName();
            File file = new File(fileName);
            file.delete();
        }
        deviceFileService.deleteByPrimaryKey(id);
        return Result.SUCCESS;
    }

    @GetMapping("/device-files/download/{uuid}")
    public void downloadFile(@PathVariable String uuid) throws IOException
    {
        DeviceFile fileInfo = deviceFileService.findDeviceFilesByUuid(uuid);
        InputStream in = Files.newInputStream(new File(fileHome + fileInfo.getStorageName()).toPath());
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileInfo.getName(), "UTF-8"));
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int length;
        while ((length = in.read(b)) > 0)
        {
            os.write(b, 0, length);
        }
        os.close();
        in.close();
    }

    /**
     * 设备目录文件上传
     *
     * @param deviceId
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/device-files/upload/{deviceId}")
    public Result uploadUserFile(@PathVariable Integer deviceId, MultipartFile file) throws Exception
    {
        String name = file.getOriginalFilename();
        String ext = FileUtil.parseExtName(name);
        String uuid = StringUtil.uuid();
        DeviceFile deviceFile = new DeviceFile();
        deviceFile.setDeviceId(deviceId);
        deviceFile.setUuid(uuid);
        deviceFile.setName(name);
        deviceFile.setExt(ext);
        deviceFile.setCreateTime(new Date());
        String storageName = deviceFile.getStorageName();
        File fileToUpload = new File(fileHome + storageName);
        file.transferTo(fileToUpload);
        deviceFileService.saveDeviceFile(deviceFile);
        return Result.SUCCESS;
    }

}
